<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库管理系统</title>
    <style>
        /* 基础样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
        }

        h1 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-bottom: 25px;
        }

        /* 头部按钮样式 */
        .header {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: #3498db;
            color: white;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        /* 表格容器样式 */
        .tables-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow: auto;
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 20px;
            border-top: 1px solid #eee;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        /* 数据表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .data-table th,
        .data-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .data-table th {
            background: #f8f9fa;
            font-weight: 600;
        }

        /* 加载动画 */
        .loading {
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* 表单控件样式 */
        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 5px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }

            .header {
                flex-direction: column;
            }

            .modal-content {
                width: 95%;
            }
        }
    </style>

</head>

<body>
    <div class="container">
        <h1>数据库管理系统</h1>

        <div class="header">
            <button id="refreshTables" class="btn btn-primary">
                <span id="refreshText">刷新表列表</span>
                <span id="refreshLoading" class="loading" style="display: none;"></span>
            </button>
            <button id="createTableBtn" class="btn btn-secondary">创建新表</button>
        </div>

        <div id="tablesContainer" class="tables-container">
            <!-- 表卡片将在这里动态生成 -->
        </div>
    </div>

    <!-- 表数据弹窗 -->
    <div id="tableDataModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="tableDataModalTitle">表数据</h2>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div id="tableDataAlert" class="alert" style="display: none;"></div>
                <div class="loading-container" id="tableDataLoading">
                    <div class="loading"></div>
                </div>
                <table id="tableDataTable" class="data-table" style="display: none;">
                    <thead>
                        <tr id="tableDataHeaders"></tr>
                    </thead>
                    <tbody id="tableDataBody"></tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button id="addNewItemBtn" class="btn btn-primary">添加新数据项</button>
                <button id="deleteTableBtn" class="btn btn-danger">删除此表</button>
                <button class="btn btn-secondary close-modal">关闭</button>
            </div>
        </div>
    </div>

    <!-- 创建表弹窗 -->
    <div id="createTableModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">创建新表</h2>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div id="createTableAlert" class="alert" style="display: none;"></div>
                <div class="form-group">
                    <label for="tableName" class="form-label">表名</label>
                    <input type="text" id="tableName" class="form-control" placeholder="输入表名（英文）">
                </div>

                <h3 style="margin-bottom: 15px;">列定义</h3>
                <p style="margin-bottom: 15px; color: #666;">第一列将自动创建为ID主键</p>

                <div id="columnFieldsContainer">
                    <!-- 列定义字段将在这里动态生成 -->
                </div>

                <button id="addColumnBtn" class="btn btn-secondary" style="margin-bottom: 20px;">添加列</button>
            </div>
            <div class="modal-footer">
                <button id="createTableSubmit" class="btn btn-primary">创建表</button>
                <button class="btn btn-secondary close-modal">取消</button>
            </div>
        </div>
    </div>

    <!-- 添加/编辑数据项弹窗 -->
    <div id="itemModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="itemModalTitle">添加数据项</h2>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div id="itemAlert" class="alert" style="display: none;"></div>
                <div id="itemFormContainer">
                    <!-- 表单字段将在这里动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button id="saveItemBtn" class="btn btn-primary">保存</button>
                <button class="btn btn-secondary close-modal">取消</button>
            </div>
        </div>
    </div>

    <!-- 确认删除弹窗 -->
    <div id="confirmModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h2 class="modal-title" id="confirmModalTitle">确认删除</h2>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <p id="confirmMessage">您确定要删除此项吗？</p>
            </div>
            <div class="modal-footer">
                <button id="confirmDeleteBtn" class="btn btn-danger">确认删除</button>
                <button class="btn btn-secondary close-modal">取消</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentTableName = '';
        let currentItemId = '';
        let isEditMode = false;
        let columnsCount = 0;

        // DOM元素
        const tablesContainer = document.getElementById('tablesContainer');
        const refreshTablesBtn = document.getElementById('refreshTables');
        const createTableBtn = document.getElementById('createTableBtn');
        const tableDataModal = document.getElementById('tableDataModal');
        const createTableModal = document.getElementById('createTableModal');
        const itemModal = document.getElementById('itemModal');
        const confirmModal = document.getElementById('confirmModal');
        const columnFieldsContainer = document.getElementById('columnFieldsContainer');
        const addColumnBtn = document.getElementById('addColumnBtn');

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 加载所有表
            loadTables();

            // 事件监听器
            refreshTablesBtn.addEventListener('click', loadTables);
            createTableBtn.addEventListener('click', showCreateTableModal);

            // 关闭模态框事件
            document.querySelectorAll('.close-btn, .close-modal').forEach(btn => {
                btn.addEventListener('click', () => {
                    document.querySelectorAll('.modal').forEach(modal => {
                        modal.style.display = 'none';
                    });
                });
            });

            // 模态框外部点击关闭
            document.querySelectorAll('.modal').forEach(modal => {
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) {
                        modal.style.display = 'none';
                    }
                });
            });

            // 添加列按钮
            addColumnBtn.addEventListener('click', addColumnField);

            // 创建表提交
            document.getElementById('createTableSubmit').addEventListener('click', createTable);

            // 表数据弹窗中的按钮
            document.getElementById('addNewItemBtn').addEventListener('click', showAddItemModal);
            document.getElementById('deleteTableBtn').addEventListener('click', confirmDeleteTable);

            // 确认删除按钮
            // document.getElementById('confirmDeleteBtn').addEventListener('click', executeDeleteTable);
        });

        // 加载所有表
        async function loadTables() {
            try {
                // 显示加载状态
                const refreshText = document.getElementById('refreshText');
                const refreshLoading = document.getElementById('refreshLoading');
                refreshText.textContent = '加载中...';
                refreshLoading.style.display = 'inline-block';

                // 清空当前表容器
                tablesContainer.innerHTML = '';

                const response = await fetch('/tables');
                if (!response.ok) {
                    throw new Error('获取表列表失败');
                }

                const tables = await response.json();

                if (tables.length === 0) {
                    tablesContainer.innerHTML = '<p style="grid-column: 1 / -1; text-align: center; color: #666;">没有找到任何表</p>';
                } else {
                    tables.forEach(table => {
                        const tableCard = document.createElement('div');
                        tableCard.className = 'table-card';
                        tableCard.innerHTML = `
                            <div class="table-name">${table}</div>
                            <div>点击查看数据</div>
                        `;
                        tableCard.addEventListener('click', () => showTableData(table));
                        tablesContainer.appendChild(tableCard);
                    });
                }
            } catch (error) {
                console.error('加载表列表出错:', error);
                showAlert('加载表列表出错: ' + error.message, 'danger');
            } finally {
                // 恢复按钮状态
                const refreshText = document.getElementById('refreshText');
                const refreshLoading = document.getElementById('refreshLoading');
                refreshText.textContent = '刷新表列表';
                refreshLoading.style.display = 'none';
            }
        }

        // 显示表数据
        async function showTableData(tableName) {
            try {
                currentTableName = tableName;

                // 更新模态框标题
                document.getElementById('tableDataModalTitle').textContent = `表: ${tableName}`;

                // 显示加载状态
                document.getElementById('tableDataLoading').style.display = 'flex';
                document.getElementById('tableDataTable').style.display = 'none';
                document.getElementById('tableDataAlert').style.display = 'none';

                // 显示模态框
                tableDataModal.style.display = 'flex';

                // 获取表数据
                const response = await fetch(`/tables/${tableName}/items`);
                if (!response.ok) {
                    throw new Error('获取表数据失败');
                }

                const items = await response.json();
                // 打印items
                // console.log(items);

                // 渲染表头
                const headersRow = document.getElementById('tableDataHeaders');
                headersRow.innerHTML = '';

                if (items.length > 0) {
                    // 添加操作列标题
                    Object.keys(items[0]).forEach(key => {
                        const th = document.createElement('th');
                        th.textContent = key;
                        headersRow.appendChild(th);

                    });

                    // 添加操作列标题
                    const actionsTh = document.createElement('th');
                    actionsTh.textContent = '操作';
                    headersRow.appendChild(actionsTh);
                    //打印headersRow.innerHTML
                    // console.log(headersRow.innerHTML);


                    // 渲染表体
                    const tableBody = document.getElementById('tableDataBody');
                    tableBody.innerHTML = '';

                    items.forEach(item => {
                        const row = document.createElement('tr');

                        // 添加数据单元格
                        Object.keys(item).forEach(key => {
                            const td = document.createElement('td');
                            td.textContent = item[key];
                            row.appendChild(td);
                        });

                        // 添加操作单元格
                        const actionsTd = document.createElement('td');

                        const editBtn = document.createElement('button');
                        editBtn.className = 'btn btn-secondary action-btn';
                        editBtn.textContent = '编辑';
                        editBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            showEditItemModal(tableName, item);
                        });

                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'btn btn-danger action-btn';
                        deleteBtn.textContent = '删除';
                        deleteBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            confirmDeleteItem(tableName, item.id);
                        });

                        actionsTd.appendChild(editBtn);
                        actionsTd.appendChild(deleteBtn);
                        row.appendChild(actionsTd);

                        tableBody.appendChild(row);
                    });
                } else {
                    // 表为空的情况
                    const row = document.createElement('tr');
                    const cell = document.createElement('td');
                    cell.colSpan = 1;
                    cell.textContent = '表中没有数据';
                    row.appendChild(cell);
                    document.getElementById('tableDataBody').innerHTML = '';
                    document.getElementById('tableDataBody').appendChild(row);
                }

                // 显示表格
                document.getElementById('tableDataLoading').style.display = 'none';
                document.getElementById('tableDataTable').style.display = 'table';
            } catch (error) {
                console.error('获取表数据出错:', error);
                document.getElementById('tableDataLoading').style.display = 'none';
                showAlertInModal('tableDataAlert', '获取表数据出错: ' + error.message, 'danger');
            }
        }

        // 显示创建表模态框
        function showCreateTableModal() {
            // 重置表单
            document.getElementById('tableName').value = '';
            columnFieldsContainer.innerHTML = '';
            document.getElementById('createTableAlert').style.display = 'none';

            // 添加初始的两个列字段
            addColumnField();
            addColumnField();

            // 显示模态框
            createTableModal.style.display = 'flex';
        }

        // 添加列字段
        function addColumnField() {
            columnsCount++;

            const fieldGroup = document.createElement('div');
            fieldGroup.className = 'column-fields';

            const nameInput = document.createElement('input');
            nameInput.type = 'text';
            nameInput.className = 'form-control';
            nameInput.placeholder = '列名 (英文)';
            nameInput.dataset.field = 'name';

            const typeInput = document.createElement('input');
            typeInput.type = 'text';
            typeInput.className = 'form-control';
            typeInput.placeholder = '类型 (如 VARCHAR(255))';
            typeInput.dataset.field = 'type';

            fieldGroup.appendChild(nameInput);
            fieldGroup.appendChild(typeInput);

            columnFieldsContainer.appendChild(fieldGroup);
        }

        // 创建表
        async function createTable() {
            try {
                const tableName = document.getElementById('tableName').value.trim();

                // 验证表名
                if (!tableName) {
                    showAlertInModal('createTableAlert', '表名不能为空', 'danger');
                    return;
                }

                if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {
                    showAlertInModal('createTableAlert', '表名只能包含字母、数字和下划线，且必须以字母或下划线开头', 'danger');
                    return;
                }

                // 收集列定义
                const columns = {
                    "id": "INT AUTO_INCREMENT PRIMARY KEY"
                };

                const fieldGroups = columnFieldsContainer.querySelectorAll('.column-fields');
                let hasError = false;

                fieldGroups.forEach(group => {
                    const nameInput = group.querySelector('input[data-field="name"]');
                    const typeInput = group.querySelector('input[data-field="type"]');

                    const name = nameInput.value.trim();
                    const type = typeInput.value.trim();

                    // 检查是否填写了部分字段
                    if ((name && !type) || (!name && type)) {
                        showAlertInModal('createTableAlert', '必须同时填写列名和类型', 'danger');
                        hasError = true;
                        return;
                    }

                    // 如果两个字段都为空，跳过
                    if (!name && !type) return;

                    // 验证列名
                    if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
                        showAlertInModal('createTableAlert', `列名"${name}"只能包含字母、数字和下划线，且必须以字母或下划线开头`, 'danger');
                        hasError = true;
                        return;
                    }

                    // 添加到列定义
                    columns[name] = type;
                });

                if (hasError) return;

                // 检查是否至少有一个自定义列
                if (Object.keys(columns).length === 1) {
                    showAlertInModal('createTableAlert', '除了ID列外，至少需要定义一个列', 'danger');
                    return;
                }

                // 准备请求数据
                const requestData = {
                    table_name: tableName,
                    columns: columns
                };

                // 发送创建表请求
                const response = await fetch('/tables', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.message || '创建表失败');
                }


                // 创建表成功后，自动添加一条临时数据
                try {
                    const tempData = {};
                    // 跳过id字段
                    Object.keys(columns).forEach(key => {
                        if (key !== 'id') {
                            // 根据类型设置默认值
                            const type = columns[key].toUpperCase();
                            if (type.includes('INT')) {
                                tempData[key] = "0";
                            } else if (type.includes('VARCHAR') || type.includes('TEXT')) {
                                tempData[key] = "temp";
                            } else if (type.includes('DATE') || type.includes('TIME')) {
                                tempData[key] = new Date().toISOString().split('T')[0];
                            } else if (type.includes('BOOLEAN') || type.includes('BOOL')) {
                                tempData[key] = "false";
                            } else {
                                tempData[key] = "temp";
                            }
                        }
                    });
                    // 添加临时数据
                    const addResponse = await fetch(`/tables/${tableName}/items`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ data: tempData })
                    });

                    if (!addResponse.ok) {
                        console.warn('添加临时数据失败，但不影响表创建');
                    }
                } catch (addError) {
                    console.warn('添加临时数据时出错:', addError);
                }


                // 显示成功消息
                // showAlertInModal('createTableAlert', '表创建成功!', 'success');
                showAlertInModal('createTableAlert', '表创建成功! 已添加一条临时数据用于确定表结构。', 'success');

                // 刷新表列表
                setTimeout(() => {
                    createTableModal.style.display = 'none';
                    loadTables();
                }, 1500);
            } catch (error) {
                console.error('创建表出错:', error);
                showAlertInModal('createTableAlert', '创建表出错: ' + error.message, 'danger');
            }
        }

        // 显示添加数据项模态框
        function showAddItemModal() {
            isEditMode = false;
            document.getElementById('itemModalTitle').textContent = `添加数据项到 ${currentTableName}`;
            document.getElementById('itemAlert').style.display = 'none';

            // 获取表结构来生成表单
            fetchTableStructureForForm();
        }

        // 显示编辑数据项模态框
        function showEditItemModal(tableName, item) {
            isEditMode = true;
            currentTableName = tableName;
            currentItemId = item.id;

            document.getElementById('itemModalTitle').textContent = `编辑 ${tableName} 的数据项`;
            document.getElementById('itemAlert').style.display = 'none';

            // 获取表结构来生成表单，并填充现有数据
            fetchTableStructureForForm(item);
        }

        // 获取表结构并生成表单
        async function fetchTableStructureForForm(existingItem = null) {
            try {
                // 显示加载状态
                const formContainer = document.getElementById('itemFormContainer');
                formContainer.innerHTML = '<div class="loading-container"><div class="loading"></div></div>';

                // 显示模态框
                itemModal.style.display = 'flex';

                // 获取表数据以推断结构 (实际应用中应该有专门的API获取表结构)
                const response = await fetch(`/tables/${currentTableName}/items`);
                if (!response.ok) {
                    throw new Error('获取表结构失败');
                }

                const items = await response.json();

                // 生成表单
                formContainer.innerHTML = '';

                if (items.length > 0) {
                    // 跳过ID字段
                    const fields = Object.keys(items[0]).filter(key => key !== 'id');

                    fields.forEach(field => {
                        const formGroup = document.createElement('div');
                        formGroup.className = 'form-group';

                        const label = document.createElement('label');
                        label.className = 'form-label';
                        label.textContent = field;
                        label.htmlFor = `item-${field}`;

                        const input = document.createElement('input');
                        input.type = 'text';
                        input.className = 'form-control';
                        input.id = `item-${field}`;
                        input.name = field;

                        // 如果是编辑模式，填充现有数据
                        if (existingItem && existingItem[field] !== undefined) {
                            input.value = existingItem[field];
                        }

                        formGroup.appendChild(label);
                        formGroup.appendChild(input);
                        formContainer.appendChild(formGroup);
                    });
                } else {
                    // 如果表为空，显示提示
                    formContainer.innerHTML = '<p>无法确定表结构，表中没有数据</p>';
                }
            } catch (error) {
                console.error('获取表结构出错:', error);
                const formContainer = document.getElementById('itemFormContainer');
                formContainer.innerHTML = `<div class="alert alert-danger">获取表结构出错: ${error.message}</div>`;
            }
        }

        // 保存数据项
        async function saveItem() {
            try {
                const formContainer = document.getElementById('itemFormContainer');
                const inputs = formContainer.querySelectorAll('input[type="text"]');
                const data = {};

                inputs.forEach(input => {
                    data[input.name] = input.value;
                });

                // 验证数据
                for (const [key, value] of Object.entries(data)) {
                    if (!value && value !== '0') {
                        showAlertInModal('itemAlert', `字段"${key}"不能为空`, 'danger');
                        return;
                    }
                }

                let response;

                if (isEditMode) {
                    // 更新现有数据项
                    response = await fetch(`/tables/${currentTableName}/items/${currentItemId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });
                } else {
                    // 创建新数据项
                    response = await fetch(`/tables/${currentTableName}/items`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ data: data })
                    });
                }

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new
                        Error(errorData.message || (isEditMode ? '更新数据项失败' : '创建数据项失败'));
                }             // 显示成功消息
                showAlertInModal('itemAlert', isEditMode ? '数据项更新成功!' : '数据项创建成功!', 'success');

                // 关闭模态框并刷新表数据
                setTimeout(() => {
                    itemModal.style.display = 'none';
                    showTableData(currentTableName);
                }, 1500);
            } catch (error) {
                console.error('保存数据项出错:', error);
                showAlertInModal('itemAlert', '保存数据项出错: ' + error.message, 'danger');
            }
        }

        // 确认删除表
        function confirmDeleteTable() {
            document.getElementById('confirmModalTitle').textContent = '确认删除表';
            document.getElementById('confirmMessage').textContent = `您确定要删除表 "${currentTableName}" 吗？此操作不可撤销！`;

            // 设置确认操作为删除表
            document.getElementById('confirmDeleteBtn').onclick = () => {
                executeDeleteTable();
                confirmModal.style.display = 'none';
            };

            confirmModal.style.display = 'flex';

        }
        async function executeDeleteTable() {
            try {
                const response = await fetch(`/tables/${currentTableName}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    throw new Error('删除表失败');
                }

                // 显示成功消息
                // showAlertnModal('tableDataAlert', '表删除成功!', 'success');
                showAlert('表删除成功!', 'success')
                // 刷新表列表
                tableDataModal.style.display = 'none';
                loadTables();

            }
            catch (error) {
                console.error('删除表出错:', error, 'danger');
                // showAlertInModal('tableDataAlert', '删除表出错: ' + error.message, 'danger');
                showAlert('删除表出错: ' + error.message, 'danger')
            }
        }

        // 确认删除数据项
        function confirmDeleteItem(tableName, itemId) {
            currentTableName = tableName;
            currentItemId = itemId;

            // 首先检查表中数据项数量
            checkItemCountBeforeDelete(tableName, itemId);
        }

        // 检查数据项数量
        async function checkItemCountBeforeDelete(tableName, itemId) {
            try {
                const response = await fetch(`/tables/${tableName}/items`);
                if (!response.ok) throw new Error('获取数据项失败');

                const items = await response.json();

                if (items.length <= 1) {
                    // showAlert('无法删除: 表中必须至少保留一项数据', 'danger');
                    showAlertInModal('tableDataAlert', '无法删除: 表中必须至少保留一项数据', 'danger')
                    return;
                }

                // 如果有多于一项数据，显示确认对话框
                document.getElementById('confirmModalTitle').textContent = '确认删除数据项';
                document.getElementById('confirmMessage').textContent = `您确定要删除ID为 ${itemId} 的数据项吗？`;
                document.getElementById('confirmDeleteBtn').onclick = () => deleteItem(tableName, itemId);
                confirmModal.style.display = 'flex';
            } catch (error) {
                console.error('检查数据项数量出错:', error);
                // showAlert('检查数据项数量出错: ' + error.message, 'danger');
                showAlertInModal('tableDataAlert', '检查数据项数量出错: ' + error.message, 'danger')
            }
        }

        // 执行删除项
        async function deleteItem(tableName, itemId) {
            try {
                const response = await fetch(`/tables/${tableName}/items/${itemId}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    throw new Error('删除数据项失败');
                }

                // showAlert('数据项删除成功!', 'success');
                showAlertInModal('tableDataAlert', '数据项删除成功!', 'success');
                confirmModal.style.display = 'none';

                // 刷新表数据
                showTableData(tableName);
            } catch (error) {
                console.error('删除数据项出错:', error);
                // showAlert('删除数据项出错: ' + error.message, 'danger');
                showAlertInModal('tableDataAlert', '删除数据项出错: ' + error.message, 'danger')
            }
        }



        // 显示提示消息
        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;

            const container = document.querySelector('.container');
            container.insertBefore(alert, container.firstChild);

            // 5秒后自动消失
            setTimeout(() => {
                alert.remove();
            }, 5000);
        }

        // 在模态框中显示提示消息
        function showAlertInModal(elementId, message, type) {
            const alertElement = document.getElementById(elementId);
            alertElement.textContent = message;
            alertElement.className = `alert alert-${type}`;
            alertElement.style.display = 'block';
        }

        // 为保存按钮添加事件监听器
        document.getElementById('saveItemBtn').addEventListener('click', saveItem);
    </script>